package com.freedom.start.sys.controller;

import com.freedom.start.common.Result;
import com.freedom.start.sys.entity.MenuEntity;
import com.freedom.start.sys.service.MenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhenggang.liu
 * @Date: 2019/12/27 18:34
 */
@Controller
@RequestMapping("/sys/menu")
public class MenuController {

    @Autowired
    MenuService menuService;

    @ModelAttribute
    public MenuEntity get(String id){
        if (StringUtils.isNotBlank(id)) {
            return menuService.get(id);
        }
        return new MenuEntity();
    }

    /**
     * 返回list页面
     * @return
     */
    @RequestMapping("/list")
    public String list(){
        return "sys/menu/list";
    }

    /**
     * 返回增加或是修改页面
     * @return
     */
    @RequestMapping("/form")
    public String form(){
        return "sys/menu/form";
    }

    /**
     * 保存
     * @param menuEntity 前台传入的属性封装到此对象中
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public Result save(@Valid MenuEntity menuEntity){
        try {
            menuService.save(menuEntity);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success("success");
    }

    /**
     * 返回json对象，供easyui使用
     * @param request 这里从中获取分页信息
     * @param menuEntity 封装搜索条件
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/dataList")
    public Map<String, Object> dataList(HttpServletRequest request, MenuEntity menuEntity){
        Map<String,Object> pageForEasyUI = menuService.findPageForEasyUI(request, menuEntity);
        return pageForEasyUI;
    }

    /**
     * 返回所有记录，combobox中使用
     * @param menuEntity
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/all")
    public List<MenuEntity> all(MenuEntity menuEntity){
        List<MenuEntity> all = menuService.findAll(menuEntity);
        return all;
    }

    /**
     * 删除，支持批量
     * @param ids 记录的id，多条用“,”分割
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete")
    public Result delete(String ids){
        try {
            menuService.deleteBatch(ids);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
        return Result.success("删除成功");
    }
}
